#ifndef SESSIONSMODEL_H
#define SESSIONSMODEL_H

#include <QAbstractListModel>

#include "../global/xnamespace.h"
#include "submodel/SessionModel.h"

class QQmlEngine;
class QJSEngine;

X_BEGIN_NAMESPACE

// 会话管理模型
class SessionsModel : public QAbstractListModel
{
    Q_OBJECT

signals:
    void sessionAdded(QString sessionId);

public:
    explicit SessionsModel(QObject *parent = 0);

    // Singleton supports
    static SessionsModel& instance();
    static const char* qmlName();
    static QObject *qmlInstance(QQmlEngine* engine, QJSEngine *jsEngine);

public:
    virtual int rowCount(const QModelIndex &parent) const override;
    virtual QVariant data(const QModelIndex &index, int role) const override;
    virtual QHash<int, QByteArray> roleNames() const override;

public:
    Q_INVOKABLE int sessionIndex(const QString &id) const;
    Q_INVOKABLE QObject *findSession(const QString& id) const;
    Q_INVOKABLE SessionModel &addSession(const QString& id, X::SessionType sessionType, bool reorder = true);
    Q_INVOKABLE SessionModel &createSession(const QString& id, X::SessionType sessionType);

    void loadDataFromDb();
    void houseKeep();

public slots:
    void onSessionLastMessageTimeChanged(const QString& sessionId, QDateTime time);

private:
    static SessionsModel *createInstance();
    static bool sessionLessThan(const SessionModel *v1, const SessionModel *v2);
    static bool sessionGreaterThan(const SessionModel *v1, const SessionModel *v2);
    static int doComparison();

    void updateSessionLastMessageActiveTime(const QString& sessionId);

private:
    QHash<int, QByteArray> m_roleNames;
    QList<SessionModel *> m_sessions;
    QMap<QString, SessionModel *> m_sessionsById;

private:
    static const char* ROLE_NAMES[];
    static const char READ_SESSIONS[];
    static const char INSERT_SESSION[];
    static const char UPDATE_SESSION_LAST_ACTIVE_TIME[];
    static const char REMOVE_SESSION[];
};

X_END_NAMESPACE

#endif // SESSIONSMODEL_H
